package org.checkboo.hopefullyengine.inversekinematics;

import org.checkboo.hopefullyengine.sceneelements.BaseObject;
import org.checkboo.math.Matrix44f;
import org.checkboo.math.Vector3f;

public class AnimationController {

	private BaseObject model;
	private Skeleton skeleton;
	private Animation animation;
	private long startTime;
	private long oldframe;
	private Boolean started = false;
	
	public AnimationController(BaseObject model, String animationName){
		this.model = model;
		this.skeleton = model.getSkeleton();
		this.animation = this.skeleton.getAnimationByName(animationName);
	}
	
	public void startAnimation(long startTime){
		this.startTime = startTime;
		this.oldframe = startTime;
		this.started = true;
	}
	
	public void stopAnimation(){
		this.started = false;
	}
	
	public boolean isStarted(){
		if(this.started)
			return true;
		else
			return false;
	}
	
	public void updateAnimation(long currentTime){
		if(isStarted()){
		long delta = (currentTime - this.startTime);
		if(delta >= this.animation.getLength()){
			delta %= this.animation.getLength();
			//oldframe = 0;
			//System.out.println("anim time: "+delta);
		}
		if((currentTime-oldframe) >= 120){
			//this.skeleton.reset();		
			//this.model.reset();
			this.skeleton.updatePose(this.animation);
			transformModel();
			oldframe = currentTime;
		}
		
		}
	}
	
	private void transformModel(){
		Vector3f[] tmpVertices = this.model.getVertices();
		Vector3f[] tmpNormals = this.model.getVertexNormals();
		Vector3f[] displayVerts = new Vector3f[tmpVertices.length];
		Vector3f[] displayNormals = new Vector3f[tmpNormals.length];
		Matrix44f[] transforms = new Matrix44f[this.skeleton.getBones().size()];
		for(int j=0; j<transforms.length; j++){
			transforms[j] = (new Matrix44f(this.skeleton.getBoneByID(j).getCompleteTransform())).multiply(this.skeleton.getBoneByID(j).getDefaultTransformInverse());
			//transforms[j] = this.skeleton.getBoneByID(j).getTotalTransform();
		}
		for(int i=0; i<this.model.getBoneAssignements().length; i++){
				displayVerts[i] = tmpVertices[i].transformRes(transforms[this.model.getBoneAssignements()[i]]);
				displayNormals[i] = tmpNormals[i].transformRes(transforms[this.model.getBoneAssignements()[i]]);
		}
		this.model.setDisplayVertices(displayVerts);
		this.model.setDisplayVertexNormals(displayNormals);
	}
}
